# -*- coding: utf-8 -*-
# noinspection PyUnresolvedReferences
from web.controllers.api import route_api
from flask import request, jsonify,g
# noinspection PyUnresolvedReferences
from application import app, db
import json, decimal
# noinspection PyUnresolvedReferences
from common.models.food.Food import Food
# noinspection PyUnresolvedReferences
from common.models.pay.PayOrder import PayOrder
# noinspection PyUnresolvedReferences
from common.libs.UrlManager import UrlManager
# noinspection PyUnresolvedReferences
from common.libs.Helper import getCurrentDate
# noinspection PyUnresolvedReferences
from common.libs.pay.PayService import PayService
# noinspection PyUnresolvedReferences
from common.libs.pay.WeChatService import WeChatService
# noinspection PyUnresolvedReferences
from common.libs.member.CartService import CartService
# noinspection PyUnresolvedReferences
from common.models.member.MemberAddress import MemberAddress
# noinspection PyUnresolvedReferences
from common.models.member.OauthMemberBind import OauthMemberBind


@route_api.route("/order/info", methods=[ "POST" ])
def orderInfo():
	resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
	req = request.values
	params_goods = req['goods'] if 'goods' in req else None
	member_info = g.member_info
	params_goods_list = []
	if params_goods:
		params_goods_list = json.loads(params_goods)

	food_dic = {}
	for item in params_goods_list:
		food_dic[item['id']] = item['number']

	food_ids = food_dic.keys()
	food_list = Food.query.filter(Food.id.in_(food_ids)).all()
	data_food_list = []
	yun_price = pay_price = decimal.Decimal(0.00)
	if food_list:
		for item in food_list:
			tmp_data = {
				"id": item.id,
				"name": item.name,
				"price": str(item.price),
				'pic_url': UrlManager.buildImageUrl(item.main_image),
				'number': food_dic[item.id]
			}
			pay_price = pay_price + item.price * int( food_dic[item.id] )
			data_food_list.append(tmp_data)

	# 获取地址
	address_info = MemberAddress.query.filter_by( is_default = 1,member_id = member_info.id,status = 1 ).first()
	default_address = ''
	if address_info:
		default_address = {
			"id": address_info.id,
			"name": address_info.nickname,
			"mobile": address_info.mobile,
			"address":"%s%s%s%s"%( address_info.province_str,address_info.city_str,address_info.area_str,address_info.address )
		}

	resp['data']['food_list'] = data_food_list
	resp['data']['pay_price'] = str(pay_price)
	resp['data']['yun_price'] = str(yun_price)
	resp['data']['total_price'] = str(pay_price + yun_price)
	resp['data']['default_address'] = default_address
	return jsonify(resp)


@route_api.route("/order/create", methods=[ "POST"])
def orderCreate():
	resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
	req = request.values
	type = req['type'] if 'type' in req else ''
	note = req['note'] if 'note' in req else ''
	express_address_id = int( req['express_address_id'] ) if 'express_address_id' in req and req['express_address_id'] else 0
	params_goods = req['goods'] if 'goods' in req else None

	items = []
	if params_goods:
		items = json.loads(params_goods)

	if len( items ) < 1:
		resp['code'] = -1
		resp['msg'] = "下单失败：没有选择商品~~"
		return jsonify(resp)

	address_info = MemberAddress.query.filter_by( id = express_address_id ).first()
	if not address_info or not address_info.status:
		resp['code'] = -1
		resp['msg'] = "下单失败：快递地址不对~~"
		return jsonify(resp)

	member_info = g.member_info
	target = PayService()
	params = {
		"note":note,
		'express_address_id':address_info.id,
		'express_info':{
			'mobile':address_info.mobile,
			'nickname':address_info.nickname,
			"address":"%s%s%s%s"%( address_info.province_str,address_info.city_str,address_info.area_str,address_info.address )
		}
	}
	resp = target.createOrder( member_info.id ,items ,params)
	#如果是来源购物车的，下单成功将下单的商品去掉
	if resp['code'] == 200 and type == "cart":
		CartService.deleteItem( member_info.id,items )

	return jsonify( resp )


@route_api.route("/order/pay", methods=[ "POST"])
def orderPay():
	resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
	member_info = g.member_info
	req = request.values
	order_sn = req['order_sn'] if 'order_sn' in req else ''
	pay_order_info = PayOrder.query.filter_by( order_sn = order_sn,member_id = member_info.id ).first()
	if not pay_order_info:
		resp['code'] = -1
		resp['msg'] = "系统繁忙。请稍后再试~~"
		return jsonify(resp)

	# 检查微信支付配置是否有效
	config_mina = app.config['MINA_APP']
	if config_mina['paykey'] == 'xxxxxxxxxxxxxx换自己的' or config_mina['mch_id'] == 'xxxxxxxxxxxx换自己的':
		# 微信支付配置无效，直接返回模拟支付信息
		app.logger.info("微信支付配置无效，使用模拟支付，订单号: %s" % order_sn)
		
		# 生成模拟的支付信息
		import time, random
		pay_info = {
			'timeStamp': str(int(time.time())),
			'nonceStr': str(random.randint(100000, 999999)),
			'package': 'prepay_id=mock_prepay_id_' + str(int(time.time())),
			'signType': 'MD5',
			'paySign': 'mock_sign_' + str(random.randint(100000, 999999))
		}
		
		# 保存模拟的prepay_id
		pay_order_info.prepay_id = 'mock_prepay_id_' + str(int(time.time()))
		db.session.add( pay_order_info )
		db.session.commit()
		
		resp['data']['pay_info'] = pay_info
		resp['msg'] = '模拟支付模式（微信支付配置未设置）'
		return jsonify(resp)

	# 以下是原来的真实支付逻辑，当微信支付配置有效时使用
	oauth_bind_info = OauthMemberBind.query.filter_by( member_id =  member_info.id ).first()
	if not oauth_bind_info:
		resp['code'] = -1
		resp['msg'] = "系统繁忙。请稍后再试~~"
		return jsonify(resp)

	notify_url = app.config['APP']['domain'] + config_mina['callback_url']

	target_wechat = WeChatService( merchant_key=config_mina['paykey'] )

	data = {
		'appid': config_mina['appid'],
		'mch_id': config_mina['mch_id'],
		'nonce_str': target_wechat.get_nonce_str(),
		'body': '订餐',  # 商品描述
		'out_trade_no': pay_order_info.order_sn,  # 商户订单号
		'total_fee': int( pay_order_info.total_price * 100 ),
		'notify_url': notify_url,
		'trade_type': "JSAPI",
		'openid': oauth_bind_info.openid
	}

	pay_info = target_wechat.get_pay_info( pay_data=data)

	#保存prepay_id为了后面发模板消息
	pay_order_info.prepay_id = pay_info['prepay_id']
	db.session.add( pay_order_info )
	db.session.commit()

	resp['data']['pay_info'] = pay_info
	return jsonify(resp)


@route_api.route("/order/callback", methods=[ "POST"])
def orderCallback():
	result_data = {
		'return_code': 'SUCCESS',
		'return_msg': 'OK'
	}
	header = {'Content-Type': 'application/xml'}
	config_mina = app.config['MINA_APP']
	target_wechat = WeChatService(merchant_key=config_mina['paykey'])
	callback_data = target_wechat.xml_to_dict( request.data )
	app.logger.info( callback_data  )
	sign = callback_data['sign']
	callback_data.pop( 'sign' )
	gene_sign = target_wechat.create_sign( callback_data )
	app.logger.info(gene_sign)
	if sign != gene_sign:
		result_data['return_code'] = result_data['return_msg'] = 'FAIL'
		return target_wechat.dict_to_xml(result_data), header
	if callback_data['result_code'] != 'SUCCESS':
		result_data['return_code'] = result_data['return_msg'] = 'FAIL'
		return target_wechat.dict_to_xml(result_data), header

	order_sn = callback_data['out_trade_no']
	pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first()
	if not pay_order_info:
		result_data['return_code'] = result_data['return_msg'] = 'FAIL'
		return target_wechat.dict_to_xml(result_data), header

	if int( pay_order_info.total_price * 100  ) != int( callback_data['total_fee'] ):
		result_data['return_code'] = result_data['return_msg'] = 'FAIL'
		return target_wechat.dict_to_xml(result_data), header

	if pay_order_info.status == 1:
		return target_wechat.dict_to_xml(result_data), header

	target_pay = PayService()
	target_pay.orderSuccess( pay_order_id = pay_order_info.id,params = { "pay_sn":callback_data['transaction_id'] } )
	target_pay.addPayCallbackData( pay_order_id = pay_order_info.id, data = request.data)
	return target_wechat.dict_to_xml(result_data), header

   
'''
web模拟回调方法
其实所有回调基本都是校验合法性 然后找到订单id，所以我们模拟就是直接传递 订单id
详解可以看博文：http://www.jixuejima.cn/article/281.html
访问Url就是  http://xxxxxx(你的ip或者域名)/api/order/callback2?id=yyyy
其中yyyy 就是你订单表的id字段的值

'''


@route_api.route( "/order/check" )
def orderCheck():
	"""检查订单状态，用于调试"""
	req = request.values
	id = int(req['id']) if 'id' in req else 0
	if not id:
		return "fail - 请提供订单ID"
	
	pay_order_info = PayOrder.query.filter_by(id=id).first()
	if not pay_order_info:
		return "fail - 订单不存在"
	
	result = {
		"订单ID": pay_order_info.id,
		"订单号": pay_order_info.order_sn,
		"状态": pay_order_info.status,
		"快递状态": pay_order_info.express_status,
		"评价状态": pay_order_info.comment_status,
		"显示状态": pay_order_info.pay_status,
		"状态描述": pay_order_info.status_desc,
		"是否在待发货列表": "是" if (pay_order_info.status == 1 and pay_order_info.express_status == -7 and pay_order_info.comment_status == 0) else "否"
	}
	
	return str(result)

@route_api.route( "/order/callback2" )
def orderCallback2():
	req = request.values
	id = int(req['id']) if 'id' in req else 0
	if not id:
		return "fail"

	# 添加调试信息
	app.logger.info("模拟回调开始，订单ID: %s" % id)
	
	# 检查订单是否存在
	pay_order_info = PayOrder.query.filter_by(id=id).first()
	if not pay_order_info:
		app.logger.error("订单不存在，ID: %s" % id)
		return "订单不存在"
	
	app.logger.info("订单当前状态: status=%s, express_status=%s, pay_status=%s, status_desc=%s" % (
		pay_order_info.status, 
		pay_order_info.express_status, 
		pay_order_info.pay_status,
		pay_order_info.status_desc
	))

	# 检查订单状态是否允许支付成功
	if pay_order_info.status not in [-8, -7]:
		app.logger.warning("订单状态不允许支付成功，当前状态: %s" % pay_order_info.status)
		return "订单状态不允许支付成功，当前状态: %s" % pay_order_info.status_desc

	target_pay = PayService()
	result = target_pay.orderSuccess(pay_order_id= id , params={ "pay_sn": "mock_pay_sn_%s" % id } )
	
	# 检查更新后的状态
	pay_order_info = PayOrder.query.filter_by(id=id).first()
	app.logger.info("订单更新后状态: status=%s, express_status=%s, pay_status=%s, status_desc=%s" % (
		pay_order_info.status, 
		pay_order_info.express_status, 
		pay_order_info.pay_status,
		pay_order_info.status_desc
	))
	
	if result:
		return "success - 订单状态已更新为: %s" % pay_order_info.status_desc
	else:
		return "fail - 支付成功处理失败"

  
  
@route_api.route("/order/ops", methods=[ "POST"])
def orderOps():
	resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
	req = request.values
	member_info = g.member_info
	order_sn = req['order_sn'] if 'order_sn' in req else ''
	act = req['act'] if 'act' in req else ''
	pay_order_info = PayOrder.query.filter_by(order_sn=order_sn, member_id=member_info.id).first()
	if not pay_order_info:
		resp['code'] = -1
		resp['msg'] = "系统繁忙。请稍后再试~~"
		return jsonify(resp)


	if act == "cancel":
		target_pay = PayService( )
		ret = target_pay.closeOrder( pay_order_id=pay_order_info.id )
		if not ret:
			resp['code'] = -1
			resp['msg'] = "系统繁忙。请稍后再试~~"
			return jsonify(resp)
	elif act == "confirm":
		pay_order_info.express_status = 1
		pay_order_info.updated_time = getCurrentDate()
		db.session.add( pay_order_info )
		db.session.commit()

	return jsonify(resp)




